package com.fmjava.service_video.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fmjava.service_video.Listener.ExcelListener;
import com.fmjava.service_video.entity.Category;
import com.fmjava.service_video.entity.excel.CategoryData;
import com.fmjava.service_video.entity.treeModel.TreeModel;
import com.fmjava.service_video.mapper.CategoryMapper;
import com.fmjava.service_video.service.CategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 科目分类 服务实现类
 * </p>
 *
 * @author fmjava
 * @since 2021-07-12
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    ExcelListener excelListener;

    @Override
    public void addCategory(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), CategoryData.class,excelListener).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<TreeModel> getTreeModelList() {
        //读取全部一级分类
        QueryWrapper<Category> onQueryWrapper = new QueryWrapper<>();
        onQueryWrapper.eq("parent_id","0");
        List<Category> oneCategories = baseMapper.selectList(onQueryWrapper);
        //读取全部二级分类
        QueryWrapper<Category> twoQueryWrapper = new QueryWrapper<>();
        twoQueryWrapper.ne("parent_id","0");
        List<Category> twoCategories = baseMapper.selectList(twoQueryWrapper);
        //封装模型数据
        List<TreeModel> list=new ArrayList<>();
        //属相复制，把前一个对象的相同名称的复制到后面一个对象(字段名要相同)
        //1、把category转换为 treeModel
        for (Category oneCategory : oneCategories) {
            TreeModel oneTreeModel = new TreeModel();
            BeanUtils.copyProperties(oneCategory, oneTreeModel);
            List<TreeModel> twoList=new ArrayList<>();
            for(Category twoCategory : twoCategories){

                //2、添加子元素 获取子分类 如果二级分类parent_id 为父级主键 则添加子元素 并转化为Tree Model
                if (oneCategory.getId().equals(twoCategory.getParentId())){
                   TreeModel twoTreeModel= new TreeModel();
                   BeanUtils.copyProperties(twoCategory, twoTreeModel);
                   twoList.add(twoTreeModel);
                }
            }
            oneTreeModel.setChildren(twoList);
            list.add(oneTreeModel);
        }

    return list;
    }
}
